﻿using System;
using System.IO;
using System.Text;
using System.Net;
using System.Web;
using System.Collections;

namespace CmEvtCli
{
    public class CmEvtCli
    {
        private static string EVENT_CREATE_PATH = "CmEvent/Create";

        private static void AddPostParameter(
            ref ArrayList postParams,
            string key,
            string value)
        {
            postParams.Add(String.Format(
                "{0}={1}",
                key,
                HttpUtility.UrlEncode(value)));
        }

        public static void CreateEvent(
            string serverUrl,
            string apiKey,
            string machineName,
            string eventSource,
            string eventText)
        {
            //
            // Create the request
            //

            WebRequest webReq = WebRequest.Create(String.Format(
                "{0}/{1}",
                serverUrl,
                EVENT_CREATE_PATH));
            webReq.Method = "POST";
            webReq.ContentType = "application/x-www-form-urlencoded";

            //
            // Encode the parameters
            //

            ArrayList evtParams = new ArrayList();
            AddPostParameter(ref evtParams, "ApiKey", apiKey);
            AddPostParameter(ref evtParams, "MachineName", machineName);
            AddPostParameter(ref evtParams, "Source", eventSource);
            AddPostParameter(ref evtParams, "Data", eventText);

            //
            // Submit the request
            //

            string parameters = String.Join(
                "&", (String[]) evtParams.ToArray(typeof(string)));
            webReq.ContentLength = parameters.Length;
            StreamWriter sw = new StreamWriter(webReq.GetRequestStream());
            sw.Write(parameters);
            sw.Close();

            HttpWebResponse webRsp = (HttpWebResponse) webReq.GetResponse();
            StreamReader sr = new StreamReader(webRsp.GetResponseStream());
            string rsp = sr.ReadToEnd();
        }
    }
}
